typedef NotifyCallback = void Function(dynamic object); //只能传一个参数

class NotifyListener {
  NotifyCallback callback;
  int id;

  NotifyListener(this.id, this.callback);
}

class NotifyCenter {
  static int sID = 0;

  static final NotifyCenter _instance = NotifyCenter._internal();

  factory NotifyCenter() {
    return _instance;
  }

  NotifyCenter._internal();

  //创建Map来记录名称
  final Map<String, List<NotifyListener>> _postNameMap = {};

  //添加监听者方法
  int addObserver(String postName, NotifyCallback callback) {
    if (_postNameMap[postName] == null) {
      _postNameMap[postName] = <NotifyListener>[];
    }

    int id = sID++;
    _postNameMap[postName]?.add(NotifyListener(id, callback));
    return id;
  }

  //发送通知传值
  void postNotification(String postName, {dynamic data}) {
    //检索Map是否含有postName
    if (_postNameMap.containsKey(postName)) {
      for (NotifyListener listener in _postNameMap[postName]!) {
        listener.callback(data);
      }
    }
  }

  //移除通知
  void removeNotification(String postName) {
    if (_postNameMap.containsKey(postName)) {
      _postNameMap.remove(postName);
    }
  }

  void removeCallback(int? id) {
    if (id == null) return;

    _postNameMap.forEach((key, value) {
      for (NotifyListener listener in value) {
        if (listener.id == id) {
          value.remove(listener);
          return;
        }
      }
    });
  }
}

class NotifyKey {
  static String strUpdateHome = 'strUpdateHome'; //(测试)
  static String newAddMsgKey = '测试'; //(添加快讯)

  static String templateEditKey = 'templateEditKey'; //(测试)
  static String toolBoxKey = 'toolBoxKey'; //(测试)

  static String newProductKey = 'newProductKey'; //(测试)
  static String getProductByCategKey = 'getProductByCategKey'; //(测试)
  static String postsProductKey = 'postsProductKey'; //(测试)
  static String categProductKey = 'categProductKey'; //(分类产品)
  static String cartProductKey = 'cartProductKey'; //(购物车)

  static String registerKey = 'registerKey'; //(注册成)
}
